<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Services;

use App\Enums\AdminActionTypeEnum;
use App\Enums\EnableStatusEnum;
use App\Exceptions\ApiException;
use App\Format\AssessTemplateFormat;
use App\Format\AssessTemplateRuleFormat;
use App\Models\AssessTemplate;
use App\Models\AssessTemplateRule;
use Illuminate\Support\Facades\DB;

class AssessTemplateService
{
    /**
     * @param array<AssessTemplateRuleFormat> $rules
     * @return bool
     */
    public function create(AssessTemplateFormat $assessTemplateFormat, array $rules)
    {
        /* @var AssessTemplate $assessTemplate */
        // AssessTemplate::query()->where('type', $assessTemplateFormat->getType())->update(['status' => EnableStatusEnum::DISABLE]);
        $assessTemplateFormat->setStatus(EnableStatusEnum::DISABLE);
        $assessTemplate = AssessTemplate::query()->create($assessTemplateFormat->toArrayNotNull());
        foreach ($rules as $assessTemplateRuleFormat) {
            $assessTemplateRuleFormat->setAssessTemplateId($assessTemplate->id);
            AssessTemplateRule::query()->create($assessTemplateRuleFormat->toArrayNotNull());
        }
        adminLog(new AssessTemplate(), AdminActionTypeEnum::CREATE, '创建模版');
        return true;
    }

    /**
     * @param array<AssessTemplateRuleFormat> $rules
     * @throws ApiException
     */
    public function update(AssessTemplateFormat $assessTemplateFormat, array $rules)
    {
        $assessTemplateId = $assessTemplateFormat->getId();
        if (empty($assessTemplateId)) {
            throw new ApiException('缺少模版 id', 1);
        }
        if ($assessTemplateFormat->getStatus() == EnableStatusEnum::ENABLE) {
            AssessTemplate::query()->where('type', $assessTemplateFormat->getType())->update(['status' => EnableStatusEnum::DISABLE]);
        }
        /** @var AssessTemplate $assessTemp */
        $assessTemp = AssessTemplate::query()->find($assessTemplateId);
        $assessTemplateFormat->setId(null);
        $assessTemp->update($assessTemplateFormat->toArrayNotNull());
        adminLog($assessTemp, AdminActionTypeEnum::UPDATE, '修改模版');
        if (empty($rules)) {
            return true;
        }
        // 如果比之前少 要删除不要的
        $alreadyHaveRules = $this->getAssessTemplateRules($assessTemplateId);
        if (count($rules) < $alreadyHaveRules->count()) {
            $putIds = [];
            foreach ($rules as $assessTemplateRuleFormat) {
                if (! empty($assessTemplateRuleFormat->getId())) {
                    array_push($putIds, $assessTemplateRuleFormat->getId());
                }
            }
            $deleteIds = array_values(array_diff($alreadyHaveRules->pluck('id')->toArray(), $putIds));
            AssessTemplateRule::query()->whereIn('id', $deleteIds)->delete();
        }
        foreach ($rules as $assessTemplateRuleFormat) {
            $id = $assessTemplateRuleFormat->getId();
            if (empty($id)) {
                $assessTemplateRuleFormat->setAssessTemplateId($assessTemplateId);
                AssessTemplateRule::query()->create($assessTemplateRuleFormat->toArrayNotNull());
            } else {
                $rule = AssessTemplateRule::query()->find($id);
                $assessTemplateRuleFormat->setId(null);
                $rule->update($assessTemplateRuleFormat->toArrayNotNull());
            }
        }
        return true;
    }

    public function delete(int $id)
    {
        try {
            DB::beginTransaction();
            $assessTemp = AssessTemplate::query()->find($id);
            AssessTemplateRule::query()->where('assess_template_id', $id)->delete();
            $assessTemp->delete();
            adminLog(new AssessTemplate(), AdminActionTypeEnum::DELETE, '删除模版');
            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            throw new ApiException($e->getMessage(), 1);
        }
    }

    public function getList(int $page, int $pageSize, array $search)
    {
        $builder = AssessTemplate::query();
        if (isset($search['type'])) {
            $builder->where('type', $search['type']);
        }
        if (isset($search['name'])) {
            $builder->where('name', 'like', '%' . $search['name'] . '%');
        }
        $count = $builder->count();
        $list = $builder
            ->skip(($page - 1) * $pageSize)
            ->take($pageSize)
            ->get()
            ->toArray();

        if (! empty($search)) {
            adminLog(new AssessTemplate(), AdminActionTypeEnum::SELECT, '查看模版列表');
        }
        return [
            'count' => $count,
            'page' => $page,
            'page_size' => $pageSize,
            'list' => $list,
        ];
    }

    public function getTempToAssess(int $page, int $pageSize, array $search)
    {
        $builder = AssessTemplate::query()->where('status', EnableStatusEnum::ENABLE);
        if (isset($search['type'])) {
            $builder->where('type', $search['type']);
        }
        if (isset($search['name'])) {
            $builder->where('name', 'like', '%' . $search['name'] . '%');
        }
        $count = $builder->count();
        $list = $builder
            ->skip(($page - 1) * $pageSize)
            ->take($pageSize)
            ->get()
            ->toArray();

        return [
            'count' => $count,
            'page' => $page,
            'page_size' => $pageSize,
            'list' => $list,
        ];
    }

    public function detail(int $id)
    {
        adminLog(new AssessTemplate(), AdminActionTypeEnum::SELECT, '查询模版详情');
        return AssessTemplate::query()->with('rules')->find($id);
    }

    public function status(int $id, int $status)
    {
        /** @var AssessTemplate $assessTemp */
        $assessTemp = AssessTemplate::query()->find($id);
        if ($status == EnableStatusEnum::ENABLE) {
            AssessTemplate::query()->where('type', $assessTemp->type)->update(['status' => EnableStatusEnum::DISABLE]);
        }
        /*
        if ($status == EnableStatusEnum::DISABLE) {
            $enableCount = AssessTemplate::query()
                ->where('status', EnableStatusEnum::ENABLE)
                ->where('type', $assessTemp->type)
                ->count();
            if ($enableCount <= 1) {
                throw new ApiException('关闭后没有可用的模版', 1);
            }
        }
        */
        $assessTemp->status = $status;
        $assessTemp->save();
        return true;
    }

    private function getAssessTemplateRules(int $assessTemplateId)
    {
        return AssessTemplateRule::query()->where('assess_template_id', $assessTemplateId)->get();
    }
}
